package com.rk.app.poll.server;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.rk.app.poll.client.Poll;
import com.rk.app.poll.client.PollResponse;
import com.rk.app.poll.client.PollService;

/**
 * The server side implementation of the RPC service.
 */
public class PollServiceImpl extends RemoteServiceServlet implements PollService {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public Poll[] getAllActivePolls() {
		// TODO Auto-generated method stub
		return null;
	}

	public Poll[] getAllPolls() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String query = "select from " + Poll.class.getName();
		try {
			List<?> p = (List<?>) pm.newQuery(query).execute();
			Poll[] polls = new Poll[p.size()];
			for (int i = 0; i < polls.length; i++) {
				polls[i] = (Poll) p.get(i);
			}
			return polls;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// TODO Auto-generated method stub
		return null;
	}

	@SuppressWarnings("unchecked")
	public Poll getPoll(String id) {
		// UserService userService = UserServiceFactory.getUserService();
		// User user = userService.getCurrentUser();
		// if (user == null) {
		// // throw new RuntimeException("Please login to view this page.");
		// return null;
		// }

		PersistenceManager pm = PMF.get().getPersistenceManager();
		String query = "id == " + id;
		List<Poll> polls = null;
		try {
			polls = (List<Poll>) pm.newQuery(Poll.class, query).execute();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return polls.get(0);
	}

	public PollResponse[] getPollResponse(String id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String query = "select from " + PollResponse.class.getName() + " where pollId==" + id;
		try {
			List<?> pr = (List<?>) pm.newQuery(query).execute();
			PollResponse[] res = new PollResponse[pr.size()];
			for (int i = 0; i < res.length; i++) {
				res[i] = (PollResponse) pr.get(i);
			}
			return res;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// TODO Auto-generated method stub
		return null;
	}

	public String greetServer(String input) {
		String serverInfo = getServletContext().getServerInfo();
		String userAgent = getThreadLocalRequest().getHeader("User-Agent");
		return "Hello, " + input + "!<br><br>I am running " + serverInfo + ".<br><br>It looks like you are using:<br>"
				+ userAgent;
	}

	public String savePoll(Poll poll) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(poll);
		} finally {
			pm.close();
		}

		return poll.getId().toString();
	}

	@SuppressWarnings("unchecked")
	public String savePollResponse(PollResponse response) {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		String returnVal = "error";
		if (user != null) {
			PersistenceManager pm = PMF.get().getPersistenceManager();
			if (response.getUserId() == null || response.getUserId().trim().equals("")) {
				response.setUserId(user.getNickname().toString() + "(" + user.getEmail() + ")");
			}
			String query = "pollId == " + response.getPollId() + " && userId == '" + response.getUserId() + "'";
			List<PollResponse> polls = (List<PollResponse>) pm.newQuery(PollResponse.class, query).execute();
			response.setTime(SimpleDateFormat.getDateTimeInstance().format(new Date()));
			try {
				if (polls.isEmpty()) {
					pm.makePersistent(response);
					returnVal = "save";
				} else {
					PollResponse pr = polls.get(0);
					pr.setComments(response.getComments());
					pr.setSelectedChoice(response.getSelectedChoice());
					pr.setTime(response.getTime());
					returnVal = "update";
				}
			} finally {
				pm.close();
			}
		}
		return returnVal;
	}

	public String getSignInURL(String uri) {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		String url = "";
		if (user != null) {
			url = user.getNickname() + " |<a href='" + userService.createLogoutURL(uri) + "'>Sign out</a>";
		} else {
			url = "<a href='" + userService.createLoginURL(uri) + "'>Sign in</a>";
		}
		return url;
	}
}
